<?php

/*
 * core/auth.php
 *
 * provide authentification interface
 */

class Auth
{
	/*
	 * authenticate()
	 * return true/false
	 */
	public static function authenticate( $username, $password )
	{
		require_once( 'database_fct.php' );

		$ret = CoreDBFct::checkPassword( $username, $password );

		if( !$ret ) return false;

		if( is_null($u = CoreDBFct::getUser( $username )) )
		{
			Log::error( 'unable to retrieve user information for "'.$username.'"' );
			return false;
		}

		if( is_null($p = CoreDBFct::listCallPermissionsForUser( $username )) )
		{
			Log::error( 'unable to retrieve user permissions for "'.$username.'"' );
			return false;
		}
		
		$perms = array();
		foreach( $p as $item )
		{
			$svcname = $item['service']['name'];
			$svcid = $item['service']['id'];
			$mthname = $item['method']['name'];
			$mthid = $item['method']['id'];

			if( !isset($perms[ $svcname ]) )
				$perms[ $svcname ] = array();

			// we skip service id since we don't use it
			$perms[$svcname][$mthname] = $mthid;
		}

		// set session variable
		$_SESSION['core']['user']['authenticated'] = true;
		$_SESSION['core']['user']['name'] = $username;
		$_SESSION['core']['user']['id'] = $u['id'];
		$_SESSION['core']['user']['group'] = array();
		$_SESSION['core']['permissions'] = $perms; 

		return true;
	}

	/*
	 * logout()
	 * return true;
	 */
	public static function logout()
	{
		// set session variable
		$_SESSION['core']['user']['authenticated'] = false;
		$_SESSION['core']['user']['name'] = '';
		$_SESSION['core']['user']['id'] = -1;
		$_SESSION['core']['user']['group'] = array();
		$_SESSION['core']['permissions'] = array();

		return true;
	}

	/*
	 * isAuthenticate()
	 * return true/false
	 */
	public static function isAuthenticate()
	{
		return $_SESSION['core']['user']['authenticated'];
	}

	/*
	 * getUsername()
	 * return username as string
	 */
	public static function getUsername()
	{
		return $_SESSION['core']['user']['name'];
	}

	/*
	 * isCallAllowed()
	 * return true/false
	 */
	public static function isCallAllowed( $serviceName, $methodName )
	{
		if( isset($_SESSION['core']['permissions'][$serviceName][$methodName]) )
			return true;
		return false;
	}


}

?>
